package com.team9.fitness.controller;

import com.team9.fitness.entity.ExerciseRecord;
import com.team9.fitness.service.ExerciseRecordService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运动记录管理控制器
 * 
 * 提供运动记录的全生命周期管理功能：
 * - 开始运动：支持单用户同时只能进行一项运动
 * - 结束运动：记录运动时长、心率、速度等数据
 * - 查询记录：支持按状态、时间范围筛选
 * - 健康监控：集成心率健康状态评估
 * 
 * 支持的运动类型：
 * - 跑步类：显示速度数据
 * - 瑜伽类：显示心率数据
 * - 其他运动：基础记录功能
 */
@RestController
@RequestMapping("/api/exercise-records")
@Slf4j
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
public class ExerciseRecordController {

    @Autowired
    private ExerciseRecordService exerciseRecordService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 开始运动（异步回调版本）
     */
    @PostMapping("/start")
    public java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> startExercise(
            @RequestBody ExerciseRecord exerciseRecord) {
        java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> future = new java.util.concurrent.CompletableFuture<>();

        try {
            // 验证必要字段
            if (exerciseRecord.getUserId() == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户ID不能为空");
                future.complete(ResponseEntity.ok(response));
                return future;
            }

            if (exerciseRecord.getExerciseId() == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "运动ID不能为空");
                future.complete(ResponseEntity.ok(response));
                return future;
            }

            log.info("开始运动: userId={}, exerciseId={}",
                    exerciseRecord.getUserId(), exerciseRecord.getExerciseId());

            // 通过ZRDDS异步发布开始运动数据，让ZRDDS执行核心业务逻辑
            Map<String, Object> additionalData = new HashMap<>();
            additionalData.put("exerciseId", exerciseRecord.getExerciseId());
            additionalData.put("startTime", java.time.LocalDateTime.now().toString());

            zrddsDataExchangeService.publishExerciseDataAsync("START_EXERCISE",
                    exerciseRecord.getUserId(), "运动开始", additionalData, result -> {
                        // 异步回调处理结果
                        future.complete(ResponseEntity.ok(result));
                    });

        } catch (Exception e) {
            log.error("开始运动失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "开始失败：" + e.getMessage());
            future.complete(ResponseEntity.ok(errorResponse));
        }

        return future;
    }

    /**
     * 结束运动（异步回调版本）
     */
    @PostMapping("/{recordId}/end")
    public java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> endExercise(
            @PathVariable Long recordId,
            @RequestParam(required = false) Double avgHeartRate,
            @RequestParam(required = false) Double maxHeartRate,
            @RequestParam(required = false) Double avgSpeed,
            @RequestParam(required = false) Double maxSpeed) {

        java.util.concurrent.CompletableFuture<ResponseEntity<Map<String, Object>>> future = new java.util.concurrent.CompletableFuture<>();

        try {
            log.info("结束运动: recordId={}, avgHeartRate={}, maxHeartRate={}, avgSpeed={}, maxSpeed={}",
                    recordId, avgHeartRate, maxHeartRate, avgSpeed, maxSpeed);

            // 通过ZRDDS异步发布结束运动数据，让ZRDDS执行核心业务逻辑
            Map<String, Object> additionalData = new HashMap<>();
            additionalData.put("recordId", recordId);
            additionalData.put("avgHeartRate", avgHeartRate);
            additionalData.put("maxHeartRate", maxHeartRate);
            additionalData.put("avgSpeed", avgSpeed);
            additionalData.put("maxSpeed", maxSpeed);
            additionalData.put("endTime", java.time.LocalDateTime.now().toString());

            zrddsDataExchangeService.publishExerciseDataAsync("END_EXERCISE",
                    null, "运动结束", additionalData, result -> {
                        // 异步回调处理结果
                        future.complete(ResponseEntity.ok(result));
                    });

        } catch (Exception e) {
            log.error("结束运动失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "结束失败：" + e.getMessage());
            future.complete(ResponseEntity.ok(errorResponse));
        }

        return future;
    }

    /**
     * 获取用户的所有运动记录
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getExerciseRecordsByUserId(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();

        try {
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserId(userId);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户运动记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定状态的运动记录
     */
    @GetMapping("/user/{userId}/status/{status}")
    public ResponseEntity<Map<String, Object>> getExerciseRecordsByUserIdAndStatus(
            @PathVariable Long userId, @PathVariable String status) {
        Map<String, Object> response = new HashMap<>();

        try {
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserIdAndStatus(userId, status);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户状态运动记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定日期的运动记录
     */
    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<Map<String, Object>> getExerciseRecordsByUserIdAndDate(
            @PathVariable Long userId, @PathVariable String date) {
        Map<String, Object> response = new HashMap<>();

        try {
            LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserIdAndDate(userId, dateTime);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户日期运动记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定运动的记录
     */
    @GetMapping("/user/{userId}/exercise/{exerciseId}")
    public ResponseEntity<Map<String, Object>> getExerciseRecordsByUserIdAndExerciseId(
            @PathVariable Long userId, @PathVariable Long exerciseId) {
        Map<String, Object> response = new HashMap<>();

        try {
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserIdAndExerciseId(userId,
                    exerciseId);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户运动记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据ID获取运动记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getExerciseRecordById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            ExerciseRecord record = exerciseRecordService.getExerciseRecordById(id);
            if (record != null) {
                response.put("success", true);
                response.put("data", record);
            } else {
                response.put("success", false);
                response.put("message", "运动记录不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取运动记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除运动记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteExerciseRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            exerciseRecordService.deleteExerciseRecord(id);
            response.put("success", true);
            response.put("message", "运动记录删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除运动记录失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
